import {Button, Divider, Dropdown, Form, Icon, Menu, message, Popconfirm, Upload, Tag,Tooltip} from 'antd';
import React, {useRef, useState} from 'react';
import {FormComponentProps} from 'antd/es/form';
import { PlusOutlined } from '@ant-design/icons';
import {PageHeaderWrapper} from '@ant-design/pro-layout';
import ProTable, {ActionType, ProColumns, UseFetchDataAction} from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';
import {TableListItem} from './data.d';
import {queryUser, addUser, updateUser, removeUser, queryClassgrade} from './service';
import XLSX from 'xlsx';
import {ArrStringFun} from "@/utils/myUtils";
interface TableListProps extends FormComponentProps {
}

const TableList: React.FC<TableListProps> = () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [stepFormValues, setStepFormValues] = useState({});
  const actionRef = useRef<ActionType>();
  const columns: ProColumns<TableListItem>[] = [
    {
      title: '用户名称',
      dataIndex: 'username',
    },
    {
      title: '用户课程',
      dataIndex: 'course',
      render(arr) {
        return (
          arr.map(item => {
            if(item.course_name != null){
              return <Tag color="orange">{item.course_name}</Tag>;
            }else{
              return <Tag color="green">未选课</Tag>;
          }

          })
        )
      }
    },
    {
      title: '用户学号或工号',
      dataIndex: 'student_number',
    },
    {
      title: '用户权限',
      dataIndex: 'permissions',
      render(data) {
        let color = "";
        if(data == 1){
          data = "超级管理员"
          color = "magenta"
        }
        if(data == 2){
          data = "管理员"
          color = "volcano"
        }
        if(data == 3){
          data = "老师"
          color = "blue"
        }
        if(data == 4){
          data = "学生"
          color = "purple"
        }
          return (
            <Tag color={color}>
              {data}
            </Tag>
          );
        }
    },
    {
      title: '用户班级或部门',
      dataIndex: 'class_name',
    },

    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a
            onClick={() => {
              handleUpdateModalVisible(true);
              setStepFormValues(record);
            }}
          >
            修改
          </a>
          <Divider type="vertical"/>
          <Popconfirm
            title="您确定要删除吗？"
            icon={<Icon type="question-circle-o" style={{ color: 'red' }} />}
            onConfirm={async()=>{
              const hide = message.loading('正在删除');
              try {
                let data = await removeUser({
                  id: record.key
                });
                if(data.data == true){
                  actionRef.current.reload();
                  hide();
                  message.success('删除成功');
                }
                return true;
              } catch (error) {
                hide();
                message.error('删除失败，请重试');
                return false;
              }}}>
            <a>删除</a>
          </Popconfirm>
        </>
      ),
    },
  ];

  /**
   * 添加节点
   * @param fields
   */
  const handleAdd = async (fields: any) => {
    const hide = message.loading('正在添加');
    try {
      let data = await addUser({
        ...fields
      });
      hide();
      if (data.msg == "执行成功") {
        message.success('添加成功');
        return true;

      } else {
        message.success('添加失败');
        return false;

      }


    } catch (error) {
      hide();
      message.error('添加失败请重试！');
      return false;
    }
  };

  /**
   * 更新节点
   * @param fields
   */
  const handleUpdate = async (fields: any) => {
    const hide = message.loading('正在修改');
    try {
      let result = await updateUser({
        ...fields
      });
      if(result.data.success == "ok"){
        hide();
        message.success('修改成功');
        return true;
      }
    } catch (error) {
      hide();
      message.error('修改失败请重试！');
      return false;
    }
  };
  const uploadprops = {
    // 这里我们只接受excel2007以后版本的文件，accept就是指定文件选择框的文件类型
    accept: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    name: 'file',
    headers: {
      authorization: 'authorization-text',
    },
    showUploadList: false,
    // 把excel的处理放在beforeUpload事件，否则要把文件上传到通过action指定的地址去后台处理
    // 这里我们没有指定action地址，因为没有传到后台
    beforeUpload: (file, fileList) => {
      var rABS = true;
      const f = fileList[0];
      var reader = new FileReader();
      reader.onload = function (e) {
        var data = e.target.result;
        if (!rABS) data = new Uint8Array(data);
        var workbook = XLSX.read(data, {
          type: rABS ? 'binary' : 'array'
        });
        // 假设我们的数据在第一个标签
        var first_worksheet = workbook.Sheets[workbook.SheetNames[0]];
        // XLSX自带了一个工具把导入的数据转成json
        var jsonArr = XLSX.utils.sheet_to_json(first_worksheet, {header:1});
        // 通过自定义的方法处理Json，比如加入state来展示
        jsonArr.slice(1).forEach(item=>{
          let data = {
           username:item[0],
            permissions:item[1],
            class_id:item[2],
            student_number:item[3],
          }
          handleAdd(data);
        })
        actionRef.current.reload();
      };
      if (rABS) reader.readAsBinaryString(f); else reader.readAsArrayBuffer(f);
      return false;
    }
  };
  return (
    <PageHeaderWrapper>
      <ProTable<TableListItem>
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="key"
        toolBarRender={(action, {selectedRows}) => [
        <Button icon={<PlusOutlined />} type="primary" onClick={() => handleModalVisible(true)}>
          新建
        </Button>,
        <Upload {...uploadprops}>
          <Tooltip title='导入excel文件'>
            <Button  type="primary" >
              <Icon type="upload" /> 导入Excel
            </Button>
          </Tooltip>
        </Upload>,
        selectedRows && selectedRows.length > 0 && (
          <Dropdown
            overlay={
              <Menu
                onClick={async e => {
                  if (e.key === 'remove') {
                    const hide = message.loading('正在删除');
                    try {
                      let data = await removeUser({
                        id:  ArrStringFun(selectedRows.map(row => row.key)),
                      });
                      if(data.data == true){
                        actionRef.current.reload();
                        hide();
                        message.success('删除成功');
                      }
                      return true;
                    } catch (error) {
                      hide();
                      message.error('删除失败，请重试');
                      return false;
                    }}
                }}
                selectedKeys={[]}
              >
                <Menu.Item key="remove">批量删除</Menu.Item>
              </Menu>
            }
          >
            <Button>
              批量操作 <Icon type="down"/>
            </Button>
          </Dropdown>
        ),
      ]}
        request={params => queryUser(params)}
        columns={columns}
        rowSelection={{}}
        />
        <CreateForm
          onSubmit={async value => {
            const success = await handleAdd(value);
            if (success) {
              handleModalVisible(false);
              actionRef.current.reload();
            }
          }}
          onCancel={() => handleModalVisible(false)}
          modalVisible={createModalVisible}
        />
        {stepFormValues && Object.keys(stepFormValues).length ? (
          <UpdateForm
            onSubmit={async value => {
              const success = await handleUpdate(value);
              if (success) {
                handleModalVisible(false);
                setStepFormValues({});
                actionRef.current.reload();
              }
            }}
            onCancel={() => {
              handleUpdateModalVisible(false);
              setStepFormValues({});
            }}
            updateModalVisible={updateModalVisible}
            values={stepFormValues}
          />
        ) : null}
    </PageHeaderWrapper>
);
};
export default TableList;
